package com.haitaoit.chengquan.module.home.activity.maintenance;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.home.model.ServerDetailModel;
import com.haitaoit.chengquan.module.login.LoginActivity;
import com.haitaoit.chengquan.ui.equipment.activity.ShowPictureActivity;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.ImageCycleView;
import com.haitaoit.chengquan.view.Img;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ServerDetailActivity extends BaseActivity {
    @ViewInject(R.id.topImg)
    ImageCycleView topImg;
    @ViewInject(R.id.detail_title)
    TextView       detail_title;
    @ViewInject(R.id.reference_price)
    TextView       reference_price;
    @ViewInject(R.id.addtime)
    TextView       addtime;
    @ViewInject(R.id.type_name)
    TextView       type_name;
    @ViewInject(R.id.credit_rating)
    TextView       credit_rating;
    @ViewInject(R.id.company_name)
    TextView       company_name;
    @ViewInject(R.id.company_address)
    TextView       company_address;
    @ViewInject(R.id.describe)
    TextView       describe;
    @ViewInject(R.id.server_detail_go)
    TextView       server_detail_go;
    @ViewInject(R.id.scrollview)
    ScrollView     scrollview;


    private String            id;
    private ServerDetailModel model;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_server_detail);
        setTitle_V("服务详情");
        setLeftShow(1, R.mipmap.left);
        setRightShow(1, R.mipmap.img56);
        backLeft_V();
        ViewUtils.inject(this);


        DisplayMetrics metrics = getResources().getDisplayMetrics();
        ViewGroup.LayoutParams lp1 = topImg.getLayoutParams();
        lp1.height = 4 * metrics.widthPixels / 5;
        topImg.setLayoutParams(lp1);
        id = getIntent().getStringExtra("id");
        httpGetservice_model();

        getRight_V().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                httpGetAppshare();
            }
        });

        if (TextUtils.equals("1", PreferenceUtils.getPrefString("account_type", ""))) {
            server_detail_go.setVisibility(View.VISIBLE);
        } else {
            server_detail_go.setVisibility(View.GONE);
        }


    }

    @Override
    protected void onResume() {
        super.onResume();
        //设置ScrollView自动滚动到顶部
        scrollview.fullScroll(ScrollView.FOCUS_UP);
    }

    private void httpGetAppshare() {
        int rnd = (int) Math.floor(Math.random() * 9000 + 1000);
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("rnd", rnd + ""));
        String sign = GetSign.genPackageSign(list);
        showProgrees("加载中，请稍等....");
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("rnd", rnd + "");
        params.addQueryStringParameter("sign", sign);
        HttpUtilsSingle.doGet(this, false, Constant.GetAppshare, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String jsonString = responseInfo.result.toString();
                try {
                    JSONObject json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            hideProgree();
                            return;
                        case 0:// 成功
                            JSONObject js = new JSONObject(Response);
                            hideProgree();
                            share(js.getString("img"), js.getString("title"), js.getString("content"), js.getString("url"));
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    hideProgree();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
                hideProgree();
            }
        });
    }

    public void share(final String img_url, final String title, final String context, final String link_url) {
        Dialog dlg = DialogUtil.ShowShareDialog(this, new BackCall() {
            @Override
            public void deal(int which, Object... obj) {
                UMImage img = new UMImage(ServerDetailActivity.this, img_url);
                switch (which) {
                    case R.id.share_friends:// 朋友圈
                        new ShareAction(ServerDetailActivity.this)
                                .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                                .setCallback(umShareListener)
                                .withTitle(title).withText(context)
                                .withTargetUrl(link_url).withMedia(img)
                                .share();
                        break;
                    case R.id.share_wxfriends:// 微信好友
                        new ShareAction(ServerDetailActivity.this)
                                .setPlatform(SHARE_MEDIA.WEIXIN)
                                .setCallback(umShareListener)
                                .withTitle(title).withText(context)
                                .withTargetUrl(link_url).withMedia(img)
                                .share();
                        break;
                    case R.id.share_sina:// 新浪
                        new ShareAction(ServerDetailActivity.this)
                                .setPlatform(SHARE_MEDIA.SINA)
                                .setCallback(umShareListener)
                                .withTitle(title).withText(context)
                                .withTargetUrl(link_url)
                                // .withMedia(img)
                                .share();
                        break;
                    case R.id.share_QQfriends:// QQ好友
                        new ShareAction(ServerDetailActivity.this)
                                .setPlatform(SHARE_MEDIA.QQ)
                                .setCallback(umShareListener)
                                .withTitle(title).withText(context)
                                .withTargetUrl(link_url)
                                //                                .withMedia(img)
                                .share();
                        break;
                }
                super.deal(which, obj);
            }
        });
        dlg.setCanceledOnTouchOutside(true);
        dlg.show();

        DisplayMetrics metric = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels; // 屏幕宽度（像素）
        WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
        params.width = width;
        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        dlg.getWindow().setAttributes(params);
    }

    /**
     * 友盟分享回调
     */
    UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            ToastUtils.showToast("分享成功");
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToastUtils.showToast("分享失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            //            ToastUtils.showToast("分享取消了");
        }
    };

    //添加onActivityResult
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }


    @OnClick({R.id.server_detail_go, R.id.company_address,})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.company_address:
                Intent intent = new Intent(this, MapGpsActivity.class);
                intent.putExtra("longitude", model.getLongitude());
                intent.putExtra("latitude", model.getLatitude());
                startActivity(intent);
                break;
            //                预约服务
            case R.id.server_detail_go:

                if (!TextUtils.equals("7", PreferenceUtils.getPrefString("type_id_need_7", ""))) {
                    if (PreferenceUtils.getPrefString("user_id", "").equals("")) {
                        Intent intentA = new Intent(ServerDetailActivity.this, LoginActivity.class);
                        intentA.putExtra("tag", "0");
                        startActivity(intentA);
                    } else if (!TextUtils.isEmpty(PreferenceUtils.getPrefString("user_id", "")) && PreferenceUtils.getPrefString("account_type", "").equals("1")) {
                        Intent intentB = new Intent(ServerDetailActivity.this, ServerOrderActivity.class);
                        intentB.putExtra("id", id);
                        intentB.putExtra("fuwuseven", "fuwuseven");
                        startActivity(intentB);
                    } else {
                        ToastUtils.showToast("该账号不是需求商！");
                    }
                    PreferenceUtils.setPrefString("type_id_need_7", "");
                    return;
                }

                Dialog dlg = DialogUtil.showInfoDialog2(ServerDetailActivity.this,
                        "预约本服务，服务商将在您预约的时段上门评估价格并服务！", "再想想", "确定预约", new BackCall() {
                            public void deal(int which, Object... obj) {
                                switch (which) {
                                    case R.id.cancel:// 确定
                                        if (PreferenceUtils.getPrefString("user_id", "").equals("")) {
                                            Intent intent = new Intent(ServerDetailActivity.this, LoginActivity.class);
                                            intent.putExtra("tag", "0");
                                            startActivity(intent);
                                        } else if (!TextUtils.isEmpty(PreferenceUtils.getPrefString("user_id", "")) && PreferenceUtils.getPrefString("account_type", "").equals("1")) {
                                            Intent intent = new Intent(ServerDetailActivity.this, ServerOrderActivity.class);
                                            intent.putExtra("id", id);
                                            intent.putExtra("seven", "seven");
                                            startActivity(intent);
                                        } else {
                                            ToastUtils.showToast("该账号不是需求商！");
                                        }
                                        break;
                                }
                                super.deal(which);
                            }
                        });
                dlg.setCanceledOnTouchOutside(true);
                dlg.show();
                break;
        }
        super.onClick(v);
    }

    private void httpGetservice_model() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("id", id));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("id", id);
        params.addQueryStringParameter("sign", sign);
        showProgrees("正在加载中,请稍等.....");
        HttpUtilsSingle.doGet(this, false, Constant.Getservice_model, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            hideProgree();
                            return;
                        case 0:// 成功
                            model = gson.fromJson(Response, ServerDetailModel.class);
                            if (model.getImg_list() != null && model.getImg_list().size() > 0) {
                                topImg.setImageResources(model.getImg_list(), listener);
                            }
                            detail_title.setText(model.getTitle());
                            if (model.getType().equals("7")) {
                                reference_price.setText("¥ " + model.getReference_price_low() + "～¥ " + model.getReference_price_high()+" 元");
                            } else {
                                reference_price.setText("¥ " + model.getReference_price_low()+" 元");
                            }
                            addtime.setText("发布：" + model.getAddtime());
                            type_name.setText("分类：" + model.getType_name());
                            company_name.setText("供应商：" + model.getCompany_name());
                            credit_rating.setText(model.getCredit_rating() + "%");
                            company_address.setText("地址：" + model.getCompany_address());
                            describe.setText(model.getDescribe());
                            hideProgree();
                            return;
                    }
                } catch (JSONException e) {
                    hideProgree();
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
                hideProgree();
            }
        });
    }

    /**
     * 轮播图点击事件
     */
    ImageCycleView.ImageCycleViewListener listener = new ImageCycleView.ImageCycleViewListener() {
        @Override
        public void displayImage(Img img, ImageView imageView) {
            ImageLoader.getInstance().displayImage(img.getImg_url(), imageView);
        }

        @Override
        public void onImageClick(int position, View imageView) {
            Intent intent = new Intent();
            intent.setClass(ServerDetailActivity.this, ShowPictureActivity.class);
            intent.putExtra("image_uri", model.getImg_list().get(position).getImg_url());
            startActivity(intent);

        }

        @Override
        public void onImageChange(int position, List<Img> imageUrlList) {
        }
    };

}
